import React,{Component} from 'react';
import './cart.scss';
import OneCart from './oneCart.jsx';
import { message } from 'antd';
import { getCartList } from 'api/cart'
export default class Cart extends Component{
	constructor (props) {
    super(props)
    this.state = {
      dataList: [],
      checkList: [],
      chcekAll: false,
      indetrminate: true,
      allPrice: 0,
      cart_ids: []
    }
  }
  componentDidMount () {
    this.getNewList()
  }
  getNewList () {
    getCartList().then(res => {
      if (res.code === 1) {
        this.setState({
          dataList: res.data
        })
      } else {
        if (res.code === -403) {
          this.props.history.push({
            pathname: '/login'
          })
        }
      }
    })
  }
  changeCheckList (value, ids, index) { // 子组件修改选中
    let checkList = this.state.checkList
    checkList[index] = value
    this.setState({
      checkList: checkList,
      cart_ids: [...ids, ...this.state.cart_ids]
    }, () => {
      this.calculatePrice()
    })
  }
  calculatePrice () {
    let number = 0
    this.state.checkList.forEach((item) => {
      item.forEach((i) => {
        number += (+i.goods_price * i.goods_num)
      })
    })
    this.setState({
      allPrice: number
    })
  }
  goconOrder=()=>{
    if (this.state.cart_ids.length === 0) {
      message.warning('请选择需要结算的商品！')
    } else {
      this.props.history.push({
        pathname: '/user/order/conOrder',
        state: {
          cart_ids: this.state.cart_ids
        }
      })
    }
  }
  goBack () {
    this.props.history.goBack()
  }
	render() {
		return (
			<div className="fl">
        <div className='to-back'>
          <i className='glyphicon glyphicon-back' onClick={this.goBack.bind(this)}></i>
          进货单({this.state.dataList.length})
        </div>
        {this.state.dataList.length > 0 ? this.state.dataList.map((item, index) => {
          return (
            <OneCart shopData={item} key={index} changeCheckList={(value, ids) => this.changeCheckList(value, ids, index)}/>
          )
        }) : <div style={{textAlign: 'center'}}>进货单暂无数据！</div>}
        <div className="cart_footer">
          <div className="checkAll">
            {/*<Checkbox onChange={this.checkAll}></Checkbox>*/}
          </div>
          <div>
            总计：<span>￥{this.state.allPrice}</span>
          </div>
          <div className="saveBtn" onClick={this.goconOrder}>
            结算
          </div>
        </div>
			</div>
		)
	}
}
